import React, { useEffect, useState } from 'react';
import { history } from 'umi';
import { Menu } from 'antd';
import { isUrl, isImg } from '@ant-design/pro-utils';
import Icon, { createFromIconfontCN } from '@ant-design/icons';
import { MenuDataItem } from '@umijs/route-utils';
import { matchPath, useLocation, useRouteMatch } from 'react-router-dom';
import { Access, useAccess } from '@@/plugin-access/access';

let IconFont = createFromIconfontCN({
  scriptUrl: '',
});

export function stripQueryStringAndHashFromPath(url: string) {
  return url.split('?')[0].split('#')[0];
}

/**
 * 获取打平的 menuData
 * 已 path 为 key
 * @param menuData
 * @param path
 */
export const getFlatMenus = (
  menuData: MenuDataItem[] = [],
  path: string = '/',
): {
  [key: string]: MenuDataItem;
} => {
  let menus: {
    [key: string]: MenuDataItem;
  } = {};
  menuData.forEach(item => {
    let routePath;
    if (item.path && item.path.substr(0, 1) === '/') {
      routePath = item.path;
    } else {
      routePath = path + '/' + item.path;
    }
    if (!item) {
      return;
    }

    item.path = routePath;
    menus[stripQueryStringAndHashFromPath(routePath)] = {
      ...item,
      parent: path,
    };
    menus[routePath] = {
      ...item,
      parent: path,
    };

    if (item.routes) {
      menus = { ...menus, ...getFlatMenus(item.routes, item.path) };
    }
  });

  return menus;
};

// 获取当前的选中菜单
export const getSelectedMenuKey = (
  pathname: string,
  menuData: MenuDataItem[],
): any | undefined => {
  const menus = getFlatMenus(menuData);
  if (menus[pathname]) {
    let prev = menus[pathname];

    if (prev.menu?.active) {
      prev = menus['/' + prev.menu.active];
    }

    return prev;
  } else {
    for (let pt in menus) {
      const loc = matchPath(pathname, {
        path: pt,
      });
      if (loc?.isExact) {
        let prev = menus[pt];
        if (prev.menu?.active) {
          prev = menus['/' + prev.menu.active];
        }
        return prev;
      }
    }
    // const loc = matchPath(location.pathname, {})
    //
    // console.log('s', loc)
  }

  return undefined;
};

const getIcone = (icon?: string | React.ReactNode): React.ReactNode => {
  if (typeof icon === 'string' && icon !== '') {
    if (isUrl(icon) || isImg(icon)) {
      return (
        <Icon
          component={() => (
            <img src={icon} alt="icon" className="ant-pro-sider-menu-icon" />
          )}
        />
      );
    }
    if (icon.startsWith('icon-')) {
      return <IconFont type={icon} />;
    }
    console.log('icon', icon);
  }
  return icon;
};

export default (props: { routes: any[]; collapsed: boolean }) => {
  const selected = getSelectedMenuKey(location.pathname || '/', props.routes);
  const access = useAccess();
  const [cacheRoutes, setRoutes] = useState([]);

  const getMenus = (routes: any[]) => {
    return routes
      .filter(route => {
        // if (route.menu?.hide) {
        //   return false;
        // }
        if (!access.canPermission(route.access)) {
          return false;
        }
        return true;
      })
      .map(route => {
        if (route.routes) {
          route.routes = getMenus(route.routes);
        }
        return route;
      })
      .filter(route => {
        if (route.routes && route.routes.length === 0) {
          return false;
        }
        return true;
      });
  };

  useEffect(() => {
    setRoutes(getMenus(props.routes) as any);
  }, [props.routes]);
  // console.log('match menu', getMatchMenu())

  const renderSubOrItem = (route: any, path: string) => {
    let routePath;
    if (route.path.substr(0, 1) === '/') {
      routePath = route.path;
    } else {
      routePath = path + '/' + route.path;
    }

    return route.routes ? (
      <Menu.SubMenu
        key={routePath}
        icon={getIcone(route.menu?.icon ?? '')}
        title={route.menu?.name ?? route.title}
      >
        {childRender(route.routes, routePath)}
      </Menu.SubMenu>
    ) : (
      <Menu.Item key={routePath}>
        {getIcone(route.menu?.icon ?? '')}
        <span>{route.menu?.name ?? route.title}</span>
      </Menu.Item>
    );
  };

  const childRender = (routes: any[], path: string) => {
    return routes
      .filter(route => {
        if (route.menu?.hide) {
          return false;
        }
        if (!access.canPermission(route.access)) {
          return false;
        }
        return true;
      })
      .map(route => renderSubOrItem(route, path));
  };

  return (
    <Menu
      theme="dark"
      mode="inline"
      defaultOpenKeys={selected ? [selected.parent] : []}
      selectedKeys={selected ? [selected.path] : []}
      onClick={(opt: any) => {
        history.push(opt.key);
      }}
    >
      {childRender(cacheRoutes, '/')}
    </Menu>
  );
};
